// pages/myClass/myClass.js
let request = require('../../operation/operation.js')
let topMsg = require('../../template/top_message/top_message.js')
let klassModel = require('../../models/klass.js')
let noticeModel = require('../../models/notice.js')
let userModel = require('../../models/user.js')
let bxt = require('../../utils/bxt.js') 

let klass = null,peoples = []

Page({

  /**
   * 页面的初始数据
   */
  data: {
    klass:{},
    peoples:null,
    manager:false, // 管理者有编辑班级、删除班级权限
    showWxBindView:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.refreshTopMessageView()
    klass = getApp().globalData.param
    this.setData({
      klass: klass,
      showWxBindView: userModel.showWxbindView(klass)
    })

    wx.setNavigationBarTitle({
      title: klass.uiname
    })

    this.getKlass()
    this.initRoleCell()
    this.initManager()

    // getApp().notificationCenter.register(bxt.ACTIVATE_KCLASS_MESSAGE, this, "refreshTopMessageView")
    getApp().notificationCenter.register(bxt.DELETE_STUDENT_MESSAGE, this, "handleDelStudentMessage")
    getApp().notificationCenter.register(bxt.DELETE_TEACHER_MESSAGE, this, "handleDelTeacherMessage");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    klass = null
    peoples = []
    // getApp().notificationCenter.remove(bxt.ACTIVATE_KCLASS_MESSAGE, this)
    getApp().notificationCenter.remove(bxt.DELETE_STUDENT_MESSAGE, this)
    getApp().notificationCenter.remove(bxt.DELETE_TEACHER_MESSAGE, this)
  },

  /**
   * 点击我的身份Cell事件处理函数
   */
  onSelectRole: function () {
    let role = userModel.getRole(klass), url;

    if (userModel.NORMAL == role.role) {  // 未绑定身份
      getApp().globalData.param.klass = klass
      url = '../selectRole/selectRole?klassSid=' + klass.sid;
    } else if (userModel.HEAD_TEACHER == role.role || userModel.TEACHER == role.role) {
      getApp().globalData.param = role.teacher
      url = '../teacherInfo/teacherInfo'
    } else if (userModel.PATRIARCH == role.role) {
      getApp().globalData.param = role.relations[0];      
      url = '../myStudentInfo/myStudentInfo'
    }

    wx.navigateTo({
      url: url,
    })
  },
  
  /**
   * 点击老师/学生信息处理事件
   */
  onShowPeopleInfo:function(event) {
    if (this.data.manager) {
      let currentUser = userModel.getCurrentUser()
      let people = event.currentTarget.dataset.people, url
      console.log(people)
      getApp().globalData.param = people
      if (people.headTeacher) {       
        url = '../teacherInfo/teacherInfo'
        if (currentUser.sid != people.userSid) {
          url = url + '?mode=del'
        }       
      }else {
        url = '../studentInfo/studentInfo?canDel=true'                                
      }

      wx.navigateTo({
        url: url
      })
    }
  },

  /**
   * 点击荣誉榜事件处理函数
   */
  onShowHonourList:function(evnet) {
    getApp().globalData.param = klass
    wx.navigateTo({
      url: '../honourList/honourList'
    })
  },

  onEditKlass:function() {
    getApp().globalData.param = klass
    
    wx.navigateTo({
      url: '../editClass/editClass?edit=true'      
    })
  },

  onDelKlass:function() {
    let that = this
    wx.showModal({
      title: '删除班级',
      content: '删除班级后，有关班级的信息都将不存在，是否确定删除？',
      showCancel: true,      
      success: function(res) {
        if (res.confirm) {
          that.deleteKlass()
        }
      }      
    })
  },

  handleDelStudentMessage:function(object) {
    this.handleDelMessage(object.student)
  },

  handleDelTeacherMessage:function(object) {
    this.handleDelMessage(object.teacher)
  },

  handleDelMessage:function(people) {
    for (let index = 0, length = peoples.length; index < length; index++) {
      if (peoples[index].sid == people.sid) {
        peoples.splice(index, 1)
        break
      }
    }

    this.setData({
      peoples: peoples
    })
  },

  /**
   * 获取班级信息
   */
  getKlass:function() {
    let that = this
    request.getRequest('/klass/info?klassSid=' + klass.sid, {}, true)
      .then(res => {
        var data = res.data;
        if (request.SUCCESSED == data.status) {          
          peoples = peoples.concat(data.teachers)
          peoples = peoples.concat(data.students)
          that.setData({
            peoples: peoples
          })
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        console.log(e)
      })
  },

  initRoleCell: function () {
    this.setData({
      role: userModel.getKlassRoleName(klass)
    })
  },

  initManager:function () {
    this.setData({
      manager: userModel.checkUserManager(klass, true)
    })
  },

  onShowWxBindView:function() {
    if (this.data.showWxBindView) {
      getApp().globalData.param = klass

      wx.navigateTo({
        url: '../bindClassIntroduce/bindClassIntroduce'      
      })
    }
  },

  /**
   * 删除班级
   */
  deleteKlass:function() {
    let that = this
    wx.showLoading({
      title: '请稍等',
      mask: true
    })
    let params = {'password':klass.password}
    request.deleteRequest('/klasses/' + klass.sid, params, true)
      .then(res => {
        wx.hideLoading()
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          klassModel.resetShowNoticeKlass(klass)
          getApp().notificationCenter.post(bxt.DELETE_KLASS_MESSAGE)
          getApp().autoBack('删除成功')              
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        wx.hideLoading()
        console.log(e)
      })
  }

   // onCreateActivateMessage:function() {
  //   let notice = noticeModel.getActivateNotice()

  //   if (null == notice) {
  //     this.createActivateNotice()
  //   }else {
  //     getApp().globalData.param = notice
  //     wx.navigateTo({
  //       url: '../noticePreview/noticePreview',
  //     })
  //   }
  // },

  // refreshTopMessageView: function () {
  //   topMsg.showBindClassView(this)
  // },

})